import React, { useState, useCallback, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Button, Modal, Flex, Toast } from '@ant-design/react-native';
import { ScrollView, TouchableOpacity } from 'react-native-gesture-handler';
import { IconX } from '@/rcomponents/iconx';
import AutoCompleteInput from '@/rcomponents/autoCompleteInput';
import NoninstructStore from './noninstructStore';
import RackMaterialStore from './components/rackMaterialStore';
import ScannedMaterialCard from './components/scannedMaterialCard';
import ShipRequesterScan from './components/shipRequesterScan';
import RackMaterialScanner from './components/rackMaterialScanner';
import ShipResultPage from './shipResultPage';

const styles = StyleSheet.create({
  centerScrollContainer: {
    flexGrow: 1,
    justifyContent: 'center',
  },
  emptyMoveContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
  scanFlex: {
    flex: 1,
  },
  hpadding5: {
    paddingHorizontal: 5,
  },
  moveActionFlex: {
    flex: 2,
    paddingLeft: 5,
  },
  shipTitle: {
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 16,
    paddingVertical: 10,
  },
  autocompleteWrapView: {
    position: 'absolute',
    zIndex: 1,
    left: 0,
    right: 0,
    top: 0,
  },
  autocompleteContainer: {
    marginHorizontal: 20,
    marginBottom: 10,
  },
});

const routeName = 'NonInstructShipPage';
function NonInstructShipPage({ navigation }) {
  const [scanning, setScanning] = useState(false);
  const initialShipObj = {
    visible: false,
    airport: '',
    airplaneReg: '',
    airportSuggests: [],
    airplaneRegSuggests: [],
    //airportSuggests: [
    //  'Carlos Bar',
    //  'Carlitos Bar',
    //  'João Bar',
    //  'José Bar',
    //  'Maria Bar',
    //  'Bruxa Bar',
    //  'Bruna Bar',
    //  'Carlos Foo',
    //  'Carlitos Foo',
    //  'João Foo',
    //  'José Foo',
    //  'Maria Foo',
    //  'Bruxa Foo',
    //  'Bruna Foo',
    //].map((n, i) => ({ text: n, value: i + '_' + n })),
    //airplaneRegSuggests: [
    //  'Carlos Bar',
    //  'Carlitos Bar',
    //  'João Bar',
    //  'José Bar',
    //  'Maria Bar',
    //  'Bruxa Bar',
    //  'Bruna Bar',
    //  'Carlos Foo',
    //  'Carlitos Foo',
    //  'João Foo',
    //  'José Foo',
    //  'Maria Foo',
    //  'Bruxa Foo',
    //  'Bruna Foo',
    //].map((n, i) => ({ text: n, value: i + '_' + n })),
  };
  const [shipObj, setShipObj] = useState(initialShipObj);
  const noninstructStore = NoninstructStore.useStore();
  const rackmatStore = RackMaterialStore.useStore();
  const { shipParts } = noninstructStore;
  const isEmptyShip = shipParts.length === 0;
  useEffect(() => {
    let didCancel = false;
    async function fetchAirParams() {
      const {
        airports,
        airplaneRegnos,
      } = await noninstructStore.getAirportAirplaneRegnos();
      if (!didCancel) {
        setShipObj({
          ...shipObj,
          airportSuggests: airports.map((arp) => ({
            value: arp.iataCode,
            text: arp.cityName,
          })),
          airplaneRegSuggests: airplaneRegnos.map((ars) => ({
            value: ars.value,
            text: ars.desc,
          })),
        });
      }
    }
    fetchAirParams();
    return () => {
      didCancel = true;
    };
  }, []);
  const handleMaterialScan = async (rack, materialBarcode, restPartQtyInfo) => {
    const materialRes = await noninstructStore.getMaterialByRackAndPart(
      rack.tid,
      rack.shelfName,
      materialBarcode,
    );
    /*
    materialRes.errorCode = 0
    materialRes.data= {
        amPartId: '2521535003484102',
        shelfLatticeId: '210000902',
        apPn: 'ABS5643AA29-17GN',
        apSn: '',
        apSysBatchNo: '33685',
        apName: '地板压条(FLOOR LAYERING)',
        stockNum: 3490,
        sellNum: 0,
        chooseReason: '',
        apCode: 'G17J018577',
        asdSubName: '05-01F',
        errorFlag: 0,
        /*
        amEarlier: [
          {
            srPn: 'ABS5643AA29-17GN',
            asdSubNamea: 'fff',
            barCode: 'eow',
            storeDate: new Date(),
            mayNum: 5,
          },
        ],
    };
        */
    if (materialRes.errorCode) {
      Toast.fail('扫码获取料件信息失败,请重试');
    } else {
      const { amEarlier, ...restRes } = materialRes.data;
      if (restRes.errorFlag === 1 || restRes.errorFlag === 2) {
        Toast.fail('扫描条码不存在,请扫其他码');
        return;
      } else if (restRes.errorFlag === 3) {
        Toast.fail('扫描条码库存不足,请扫其他码');
        return;
      }
      const thisPart = {
        id: restRes.amPartId,
        serial_no: restRes.apSn,
        part_no: restRes.apPn,
        barcode: restRes.apCode,
        batch_no: restRes.apSysBatchNo,
        stock_qty: restRes.stockNum,
        rack_no: restRes.asdSubName,
        rack_shelf_id: restRes.shelfLatticeId,
        name: restRes.apName,
        qty: 1,
      };
      const existPart = shipParts.find((shp) => shp.id === thisPart.id);
      if (existPart && thisPart.serial_no) {
        Toast.fail('此序号件已选择，请勿重复选择');
        return;
      }
      if ((amEarlier && amEarlier.length > 0) || !thisPart.serial_no) {
        let partQtyModalInfo = {
          visible: true,
          qty: 1,
          earlierParts: amEarlier
            ? amEarlier.map((ame) => ({
                part_no: ame.srPn,
                rack_no: ame.asdSubNamea,
                barcode: ame.barCode,
                expire_time: new Date(ame.storeDate),
                stock_qty: ame.mayNum,
              }))
            : [],
          material: thisPart,
        };
        if (amEarlier && amEarlier.length > 0) {
          partQtyModalInfo = { ...partQtyModalInfo, ...restPartQtyInfo };
        }
        if (existPart) {
          partQtyModalInfo.qty = existPart.qty;
        }
        rackmatStore.showPartQtyModal(partQtyModalInfo);
      } else {
        noninstructStore.addShipMaterial(thisPart);
        rackmatStore.addScannedPart({
          rack_no: thisPart.rack_no,
          part_no: thisPart.part_no,
          qty: 1,
        });
      }
    }
  };
  const handleChooseScanQty = (scannedMaterial) => {
    noninstructStore.addShipMaterial(scannedMaterial);
  };
  const handlePartQtyAdjust = useCallback(
    (shipPartId, newQty) => {
      noninstructStore.adjustShipMaterialQty(shipPartId, newQty);
    },
    [noninstructStore],
  );
  return (
    <>
      <ShipRequesterScan />
      <ScrollView
        contentContainerStyle={
          isEmptyShip ? styles.centerScrollContainer : undefined
        }
      >
        {isEmptyShip && (
          <View style={styles.emptyMoveContainer}>
            <IconX origin="MaterialIcons" name="filter-none" size={48} />
            <Text>尚无发料项,请扫码添加</Text>
          </View>
        )}
        <ScannedMaterialCard
          partItems={shipParts}
          qtylabel="发料数"
          onQtyAdjust={handlePartQtyAdjust}
        />
      </ScrollView>
      <Flex style={styles.hpadding5}>
        <Flex.Item style={styles.scanFlex}>
          <Button
            type={isEmptyShip ? 'primary' : 'ghost'}
            key="scan"
            onPress={() => {
              setScanning(true);
            }}
          >
            <IconX name="scan" origin="ionicons" />
            扫件
          </Button>
        </Flex.Item>

        {!isEmptyShip && (
          <Flex.Item style={styles.moveActionFlex}>
            <Button
              type="primary"
              key="submit"
              onPress={() => {
                setShipObj({
                  ...shipObj,
                  visible: true,
                });
              }}
            >
              发料
            </Button>
          </Flex.Item>
        )}
      </Flex>
      <Modal
        visible={scanning}
        onClose={() => {
          setScanning(false);
        }}
      >
        <RackMaterialScanner
          onMaterialScan={handleMaterialScan}
          onChooseScannedMaterialQty={handleChooseScanQty}
          onExitScan={() => {
            setScanning(false);
          }}
        />
      </Modal>
      <Modal popup animationType="slide-up" visible={shipObj.visible}>
        <Flex>
          <Flex.Item flex={1}>
            <TouchableOpacity
              onPress={() => {
                setShipObj({ ...shipObj, visible: false });
              }}
            >
              <IconX size={20} origin="ant" name="closecircleo" />
            </TouchableOpacity>
          </Flex.Item>
          <Flex.Item flex={15}>
            <Text style={styles.shipTitle}>发料对象</Text>
          </Flex.Item>
        </Flex>
        <AutoCompleteInput
          data={shipObj.airplaneRegSuggests}
          userStyle={{
            containerStyle: styles.autocompleteContainer,
          }}
          textExtractor={(item) => item.text}
          placeholder="机号"
          zIndex={2}
          onComplete={(item) => {
            setShipObj({
              ...shipObj,
              airplaneReg: item.value,
            });
          }}
        />
        <AutoCompleteInput
          data={shipObj.airportSuggests}
          placeholder="站点"
          userStyle={{ containerStyle: styles.autocompleteContainer }}
          textExtractor={(airport) => `${airport.value}|${airport.text}`}
          zIndex={1}
          onComplete={(item) => {
            setShipObj({
              ...shipObj,
              airport: item.value,
            });
          }}
        />
        <Flex.Item>
          <Button
            type="primary"
            loading={noninstructStore.shipMaterialParts.loading}
            onPress={async () => {
              if (shipObj.visible) {
                if (!rackmatStore.shipRequester.tid) {
                  Toast.fail('请先扫码识别领料人信息');
                  return;
                }
                if (!shipObj.airport || !shipObj.airplaneReg) {
                  Toast.fail('请填写站点及机号');
                  return;
                }
                const shipRes = await noninstructStore.shipMaterialParts(
                  shipObj.airplaneReg,
                  shipObj.airport,
                  rackmatStore.shipRequester.tid,
                  rackmatStore.shipRequester.name,
                );
                if (shipRes.errorCode) {
                  Toast.fail(shipRes.errorMsg);
                  return;
                }
                setShipObj(initialShipObj);
                rackmatStore.clearShipRequester();
                navigation.navigate(ShipResultPage.routeName, {
                  from: 'NonInstruct',
                });
              }
            }}
          >
            确定
          </Button>
        </Flex.Item>
      </Modal>
    </>
  );
}

NonInstructShipPage.routeName = routeName;
NonInstructShipPage.permission = 'RNonInstructShip';
export default NonInstructShipPage;
